"""海康"""
import os
import datetime
import base64
import hashlib
import hmac
import uuid
import pytz
import httpx

HOST = "https://192.168.100.120"
PORT = "443"
APPKEY = "20802537"
APPSECRET = "rLnPGedijw97kemakjPE"
CONTENT = 'artemis'

os.environ['NO_PROXY'] = "192.168.100.120,192.168.100.119"


def signature(secret, method, app_key, artemis, api):
    """签名"""
    timestamp = str(int(datetime.datetime.now().timestamp()) * 1000)
    # uuid
    nonce = str(uuid.uuid1())
    # signature
    secret = str(secret).encode('utf-8')
    message = (
        f"{method}\n"
        "*/*\n"
        "application/json\n"
        f"x-ca-key:{app_key}\n"
        f"x-ca-nonce:{nonce}\n"
        f"x-ca-timestamp:{timestamp}\n"
        f"/{artemis}{api}"
    ).encode('utf-8')

    signature_inner = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())
  
    header_dict = {
        "Accept": '*/*',
        "Content-Type": 'application/json',
        "X-Ca-Key": app_key,
        "X-Ca-Signature": signature_inner,
        "X-Ca-timestamp": timestamp,
        "X-Ca-nonce": nonce,
        "X-Ca-Signature-Headers": 'x-ca-key,x-ca-nonce,x-ca-timestamp'
    }

    return header_dict

def handle_auth(url):
    """authentication"""
    auth = httpx.DigestAuth('admin', 'hik12345')
    if "192.168.100.119" in url:
        auth = httpx.DigestAuth("admin", "hik12345+")
    return auth

def hi_kisapi_proxy_func(url: str = "", method: str = "", body=None):
    """前端代理"""
    request_url = 'http://192.168.100.119' + url
    # 设置认证信息
    auth1 = httpx.DigestAuth('admin', 'hik12345+')
    # 发送请求，获取响应
    if method == "GET":
        response = httpx.get(request_url, auth=auth1)
    elif method == "POST":
        response = httpx.post(request_url, data=body, auth=auth1)
    elif method == "PUT":
        response = httpx.put(request_url, data=body, auth=auth1)
    return response


def picture_check(face_pic_binary_data):
    """人脸评分"""
    api = '/api/frs/v1/face/picture/check'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    payload = {"facePicBinaryData": face_pic_binary_data}
    return httpx.post(url, headers=header_dict, json=payload, verify=False, proxies=None).json()


def get_person_info(payload):
    """获取人员详情"""
    api = '/api/resource/v1/person/condition/personInfo'  # api 的url
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def visitor_appointment_func(data, result):
    """添加访客预约"""
    api = '/api/visitor/v2/appointment'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    # 获取当前日期时间

    desired_timezone = pytz.timezone('Asia/Shanghai')  # 以中国上海时区为例
    current_datetime = datetime.datetime.now(desired_timezone)

    # 时间添加 7 天
    one_day = datetime.timedelta(days=15)

    # 格式化为 ISO 8601 格式
    iso8601_start_time = current_datetime.strftime("%Y-%m-%dT%H:%M:%S%z").replace("+0800", "+08:00")
    iso8601_end_time = (current_datetime + one_day).strftime("%Y-%m-%dT%H:%M:%S%z").replace("+0800", "+08:00")

    payload = {
        "receptionistId": data["personId"],  # 人员名称
        "visitorPermissionSet": {
            "defaultPrivilegeGroupFlag": 1,
            "privilegeGroupIds": [
                "ecc866c1-1e87-44d0-8574-30deb2307569"  # 访客组权限
            ]
        },
        "visitStartTime": iso8601_start_time,
        "visitEndTime": iso8601_end_time,
        "visitPurpose": "专家被访客人",
        "visitorInfoList": [{
            "visitorName": result["personName"],
            "gender": result["gender"],
            "phoneNo": data["phone_number"],
            "certificateType": "111",
            "certificateNo": result["certificateNo"],
            "visitorPhoto": data["faceData"],
        }]
    }

    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def visitor_sign_out_func(data):
    """访客签退"""
    api = '/api/visitor/v1/visitor/out'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    payload = {"orderId": data["orderId"]}
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def single_person_add(data):
    """添加人员信息"""
    api = '/api/resource/v2/person/single/add'  # api 的url
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    payload = {
        "personName": data["personName"],  # 人员名称
        "gender": data["gender"],
        "orgIndexCode": "2066f6c5-ad79-4dd0-ba64-e8a53f4eaeb3",  # 平台建设运维人员
        "certificateType": "111",
        "certificateNo": data["id_card"],  # 身份证
        "faces": [{
            "faceData": data["faceData"],
            "facePicBinaryData": data["faceData"]
        }]
    }
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def order_register(order_id):
    """预约登记"""
    api = '/api/visitor/v1/order/register'  # api 的url
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    # 获取当前日期时间

    desired_timezone = pytz.timezone('Asia/Shanghai')  # 以中国上海时区为例
    current_datetime = datetime.datetime.now(desired_timezone)

    # 时间添加 7 天
    one_day = datetime.timedelta(days=7)

    # 格式化为 ISO 8601 格式
    iso8601_end_time = (current_datetime + one_day).strftime("%Y-%m-%dT%H:%M:%S%z").replace("+0800", "+08:00")
    payload = {
        "orderId": order_id,  # 人员名称
        "visitorPermissionSet": {
            "defaultPrivilegeGroupFlag": 1,
            "privilegeGroupIds": [
                "ecc866c1-1e87-44d0-8574-30deb2307569"  # 访客组权限
            ]
        },
        "visitEndTime": iso8601_end_time,
    }
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def appointment_records(payload):
    """预约记录"""
    api = '/api/visitor/v2/appointment/records'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def appointment_update(data):
    """访客预约接口"""
    api = '/api/visitor/v2/appointment/update'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    # 获取当前日期时间

    desired_timezone = pytz.timezone('Asia/Shanghai')  # 以中国上海时区为例
    current_datetime = datetime.datetime.now(desired_timezone)

    # 时间添加 7 天
    one_day = datetime.timedelta(days=7)

    # 格式化为 ISO 8601 格式
    iso8601_start_time = current_datetime.strftime("%Y-%m-%dT%H:%M:%S%z").replace("+0800", "+08:00")
    iso8601_end_time = (current_datetime + one_day).strftime("%Y-%m-%dT%H:%M:%S%z").replace("+0800", "+08:00")

    payload = {
        "appointRecordId": data['appointRecordId'],
        "receptionistId": data["receptionistId"],  # 人员名称
        "visitorPermissionSet": {
            "defaultPrivilegeGroupFlag": 1,
            "privilegeGroupIds": [
                "ecc866c1-1e87-44d0-8574-30deb2307569"  # 访客组权限
            ]
        },
        "visitStartTime": iso8601_start_time,
        "visitEndTime": iso8601_end_time,
        "visitPurpose": "专家被访客人",
        "visitorInfoList": [{
            "visitorName": data["personName"],
            "gender": data["gender"],
            "phoneNo": data["phone_number"],
            "certificateType": "111",
            "certificateNo": data["certificateNo"],
            "visitorPhoto": data["faceData"],
        }]
    }

    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def person_list(payload):
    """人员列表"""
    api = '/api/resource/v2/person/personList'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def appointment_cancel(payload):
    """取消预约"""
    api = '/api/visitor/v1/appointment/cancel'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def visiting_records(payload):
    """访客记录"""
    api = '/api/visitor/v2/visiting/records'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()


def group(payload):
    """权限组"""
    api = '/api/visitor/v1/privilege/group'
    url = f"{HOST}:{PORT}/{CONTENT}{api}"
    header_dict = signature(APPSECRET, "POST", APPKEY, CONTENT, api)
    return httpx.post(url, headers=header_dict, json=payload, verify=False).json()